﻿using Daq.Devices;
using Daq.Localization;
using Daq.Services;
using Daq.ViewModels;
using Daq.ViewModels.DeviceSettingsViewModels;
using Daq.Views;
using Daq.Views.DeviceSettingsViews;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using SkiaSharp;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows;
using Telerik.Windows.Controls;
using IServiceProvider = System.IServiceProvider;

namespace Daq
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            Services = ConfigureServices();

            LocalizationManager.Manager = new LocalizationManager()
            {
                ResourceManager = GridViewResources.ResourceManager,
            };

            StyleManager.ApplicationTheme = new Windows11Theme();
            //var ColorConverter = new ColorConverter();
            //Windows11Palette.Palette.PrimaryForegroundColor = (Color)ColorConverter.ConvertFromString("#E4E32A2A");
            //Windows11Palette.Palette.SecondaryForegroundColor = (Color)ColorConverter.ConvertFromString("#9B000000");
            //Windows11Palette.Palette.TertiaryForegroundColor = (Color)ColorConverter.ConvertFromString("#72000000");
            //Windows11Palette.Palette.DisabledForegroundColor = (Color)ColorConverter.ConvertFromString("#FF000000");
            //Windows11Palette.Palette.AccentControlForegroundColor = (Color)ColorConverter.ConvertFromString("#FFFFFFFF");
            //Windows11Palette.Palette.IconColor = (Color)ColorConverter.ConvertFromString("#E4000000");
            //Windows11Palette.Palette.IconSecondaryColor = (Color)ColorConverter.ConvertFromString("#9B000000");
            //Windows11Palette.Palette.PrimaryBackgroundColor = (Color)ColorConverter.ConvertFromString("#B3FFFFFF");
            //Windows11Palette.Palette.PrimarySolidBackgroundColor = (Color)ColorConverter.ConvertFromString("#FFFFFFFF");
            //Windows11Palette.Palette.SecondaryBackgroundColor = (Color)ColorConverter.ConvertFromString("#FFEEEEEE");
            //Windows11Palette.Palette.TertiaryBackgroundColor = (Color)ColorConverter.ConvertFromString("#FFF9F9F9");
            //Windows11Palette.Palette.TertiarySmokeBackgroundColor = (Color)ColorConverter.ConvertFromString("#4D000000");
            //Windows11Palette.Palette.SubtleColor = (Color)ColorConverter.ConvertFromString("#0A000000");
            //Windows11Palette.Palette.SubtleSecondaryColor = (Color)ColorConverter.ConvertFromString("#06000000");
            //Windows11Palette.Palette.AlternativeColor = (Color)ColorConverter.ConvertFromString("#FFF3F3F3");
            //Windows11Palette.Palette.OverlayColor = (Color)ColorConverter.ConvertFromString("#FFFBFBFB");
            //Windows11Palette.Palette.PrimaryBorderColor = (Color)ColorConverter.ConvertFromString("#0F000000");
            //Windows11Palette.Palette.PrimarySolidBorderColor = (Color)ColorConverter.ConvertFromString("#FFECECEC");
            //Windows11Palette.Palette.SecondaryBorderColor = (Color)ColorConverter.ConvertFromString("#29000000");
            //Windows11Palette.Palette.TertiaryBorderColor = (Color)ColorConverter.ConvertFromString("#FFEBEBEB");
            //Windows11Palette.Palette.ButtonBorderGradientStop1Color = (Color)ColorConverter.ConvertFromString("#0E000000");
            //Windows11Palette.Palette.ButtonBorderGradientStop2Color = (Color)ColorConverter.ConvertFromString("#29000000");
            //Windows11Palette.Palette.InputBorderGradientStop1Color = (Color)ColorConverter.ConvertFromString("#0F000000");
            //Windows11Palette.Palette.InputBorderGradientStop2Color = (Color)ColorConverter.ConvertFromString("#72000000");
            //Windows11Palette.Palette.AccentControlBorderGradientStop1Color = (Color)ColorConverter.ConvertFromString("#14FFFFFF");
            //Windows11Palette.Palette.AccentControlBorderGradientStop2Color = (Color)ColorConverter.ConvertFromString("#66000000");
            //Windows11Palette.Palette.FocusColor = (Color)ColorConverter.ConvertFromString("#E4000000");
            //Windows11Palette.Palette.FocusInnerColor = (Color)ColorConverter.ConvertFromString("#B3FFFFFF");
            //Windows11Palette.Palette.MouseOverBackgroundColor = (Color)ColorConverter.ConvertFromString("#B3F9F9F9");
            //Windows11Palette.Palette.MouseOverBorderGradientStop1Color = (Color)ColorConverter.ConvertFromString("#0F000000");
            //Windows11Palette.Palette.MouseOverBorderGradientStop2Color = (Color)ColorConverter.ConvertFromString("#71000000");
            //Windows11Palette.Palette.PressedBackgroundColor = (Color)ColorConverter.ConvertFromString("#4DF9F9F9");
            //Windows11Palette.Palette.SelectedColor = (Color)ColorConverter.ConvertFromString("#0A000000");
            //Windows11Palette.Palette.SelectedMouseOverColor = (Color)ColorConverter.ConvertFromString("#06000000");
            //Windows11Palette.Palette.SelectedUnfocusedColor = (Color)ColorConverter.ConvertFromString("#FFD9D9D9");
            //Windows11Palette.Palette.StrokeColor = (Color)ColorConverter.ConvertFromString("#FFC4C4C4");
            //Windows11Palette.Palette.ReadOnlyBackgroundColor = (Color)ColorConverter.ConvertFromString("#E6F6F6F6");
            //Windows11Palette.Palette.ReadOnlyBorderColor = (Color)ColorConverter.ConvertFromString("#FFEBEBEB");
            //Windows11Palette.Palette.DisabledBackgroundColor = (Color)ColorConverter.ConvertFromString("#4DF9F9F9");
            //Windows11Palette.Palette.DisabledBorderColor = (Color)ColorConverter.ConvertFromString("#0F000000");
            //Windows11Palette.Palette.ValidationColor = (Color)ColorConverter.ConvertFromString("#FFC42B1C");
            //Windows11Palette.Palette.AccentColor = (Color)ColorConverter.ConvertFromString("#FF005FB8");
            //Windows11Palette.Palette.AccentMouseOverColor = (Color)ColorConverter.ConvertFromString("#E6005FB8");
            //Windows11Palette.Palette.AccentPressedColor = (Color)ColorConverter.ConvertFromString("#CC005FB8");
            //Windows11Palette.Palette.AccentSelectedColor = (Color)ColorConverter.ConvertFromString("#FF0078D4");
            //Windows11Palette.Palette.DisabledOpacity = 0.36;
            //Windows11Palette.Palette.ReadOnlyOpacity = 0.61;
            Windows11ThemeSizeHelper.Helper.IsInCompactMode = true;
            
           
            this.InitializeComponent();
            //LiveCharts.Configure(config => config.HasGlobalSKTypeface(SKFontManager.Default.MatchCharacter('汉')));
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            var logger = Services.GetService<ILogger>();
            base.OnStartup(e);
            // 捕获UI线程未处理异常
            DispatcherUnhandledException += (sender, args) =>
            {
                string errorMsg = $"UI线程异常：{args.Exception.Message}\n堆栈跟踪：{args.Exception.StackTrace}";
                logger?.Error(errorMsg); // 保存日志
                MessageBox.Show($"程序发生错误：{args.Exception.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                args.Handled = true; // 标记为已处理，避免程序闪退
                Shutdown(); // 可选：处理后关闭程序
            };

            // 捕获非UI线程未处理异常（如后台线程）
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                Exception ex = args.ExceptionObject as Exception;
                string errorMsg = $"非UI线程异常：{ex?.Message}\n堆栈跟踪：{ex?.StackTrace}";
                logger?.Error(errorMsg);
                MessageBox.Show($"程序发生错误：{ex?.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown();
            };
        }

        public new static App Current => (App)Application.Current;

        public IServiceProvider Services { get; }
        private static IServiceProvider ConfigureServices()
        {
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Daq\logs\Log.txt");
            var logger = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .WriteTo.Async(a => a.File(logPath,
                    outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}",//输出日期格式
                    rollingInterval: RollingInterval.Day,//日志按日保存
                    rollOnFileSizeLimit: true,          // 限制单个文件的最大长度   
                    encoding: Encoding.UTF8,            // 文件字符编码     
                    retainedFileCountLimit: 100,         // 最大保存文件数     
                    fileSizeLimitBytes: 1000 * 1024)      // 最大单个文件长度
                )
                .CreateLogger();
            logger.Information($"软件启动");

            var services = new ServiceCollection();

            //services.AddSingleton<ILogger>(
            //    new LoggerConfiguration()
            //    .MinimumLevel.Debug()
            //    .WriteTo.File("log.txt")
            //    .CreateLogger()
            //    );
            //services.AddSingleton<IMessageBoxService>(new MessageBoxService());
            services.AddSingleton<ILogger>(logger);
            services.AddSingleton<DataManagerViewModel>();
            services.AddSingleton<DaqViewModel>();
            services.AddSingleton<SettingsService>();
            services.AddSingleton<DeviceSettingsViewModel>();
            services.AddSingleton<INavigationService>(new NavigationService());
            services.AddSingleton<ConnectionViewModel>();
            services.AddSingleton<MeasurementViewModel>();
            services.AddSingleton<ChannelsViewModel>();
            services.AddSingleton<DataPreprocessViewModel>();
            services.AddSingleton<DeviceService>();
            services.AddSingleton<PlotService>();
            services.AddSingleton<DataService>();
            services.AddTransient<DataManagerView>();
            services.AddSingleton<DaqView>();
            //services.AddTransient<DeviceConfigurationView>();
            services.AddTransient<DeviceSettingsView>();
            services.AddTransient<MainWindow>();
            //services.AddTransient<DataStorageSettingView>();
            services.AddTransient<ConnectionView>();
            services.AddTransient<ChannelsView>();
            services.AddTransient<IpAddressSettingView>();
            services.AddTransient<DataPreprocessView>();
            services.AddSingleton<IDialogService, DialogService> ();
            //services.AddTransient<AboutView>();

            //新建一个DX2100实例
            //services.AddSingleton<DaqBase>(new DX2100());
            
            return services.BuildServiceProvider();
        }
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var window = Services.GetService<MainWindow>();
            window!.Show();
        }
    }
}
